import React, { useState, useEffect, useRef } from "react";

interface VoiceAssistantProps {
    isOpen: boolean;
    onClose: () => void;
}

interface VoiceMessage {
    type: "user" | "assistant";
    content: string;
    isVoice?: boolean;
}

const VoiceAssistant: React.FC<VoiceAssistantProps> = ({ isOpen, onClose }) => {
    const [messages, setMessages] = useState<VoiceMessage[]>([
        {
            type: "assistant",
            content: "你好！我是昆昆，你的语音助手。请点击麦克风开始说话！",
        },
    ]);
    const [input, setInput] = useState("");
    const [isListening, setIsListening] = useState(false);
    const [isSpeaking, setIsSpeaking] = useState(false);
    const recognitionRef = useRef<any>(null);
    const synthesisRef = useRef<SpeechSynthesis | null>(null);

    // 初始化语音识别
    useEffect(() => {
        if (
            typeof window !== "undefined" &&
            "webkitSpeechRecognition" in window
        ) {
            recognitionRef.current = new (
                window as any
            ).webkitSpeechRecognition();
            recognitionRef.current.continuous = false;
            recognitionRef.current.interimResults = false;
            recognitionRef.current.lang = "zh-CN";

            recognitionRef.current.onstart = () => {
                setIsListening(true);
            };

            recognitionRef.current.onresult = (event: any) => {
                const transcript = event.results[0][0].transcript;
                setInput(transcript);
                handleSendMessage(transcript);
            };

            recognitionRef.current.onend = () => {
                setIsListening(false);
            };

            recognitionRef.current.onerror = (event: any) => {
                console.error("语音识别错误:", event.error);
                setIsListening(false);
            };
        }

        synthesisRef.current = window.speechSynthesis;
    }, []);

    const startListening = () => {
        if (recognitionRef.current) {
            recognitionRef.current.start();
        }
    };

    const stopListening = () => {
        if (recognitionRef.current) {
            recognitionRef.current.stop();
        }
    };

    const speak = (text: string) => {
        if (synthesisRef.current) {
            setIsSpeaking(true);
            const utterance = new SpeechSynthesisUtterance(text);
            utterance.lang = "zh-CN";
            utterance.rate = 0.9;
            utterance.pitch = 1.1;

            utterance.onend = () => {
                setIsSpeaking(false);
            };

            synthesisRef.current.speak(utterance);
        }
    };

    const handleSendMessage = (messageText?: string) => {
        const text = messageText || input;
        if (!text.trim()) return;

        // 添加用户消息
        const userMessage: VoiceMessage = {
            type: "user",
            content: text,
            isVoice: !!messageText,
        };
        setMessages((prev) => [...prev, userMessage]);

        // 模拟昆昆回复
        setTimeout(() => {
            const responses = [
                "我听到了，让我来帮你处理这个问题...",
                "好的，我明白了。我的建议是...",
                "这是一个很好的问题，让我为你详细解答...",
                "谢谢你的提问，昆昆正在为你分析...",
                "我理解你的需求，让我来协助你...",
                "昆昆听到了，让我为你提供解决方案...",
                "好的，我记住了。让我来帮你...",
                "这个问题很有趣，昆昆来为你解答...",
            ];
            const randomResponse =
                responses[Math.floor(Math.random() * responses.length)];
            const assistantMessage: VoiceMessage = {
                type: "assistant",
                content: randomResponse,
                isVoice: true,
            };
            setMessages((prev) => [...prev, assistantMessage]);

            // 语音播放回复
            speak(randomResponse);
        }, 1000);

        setInput("");
    };

    const handleInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
        if (e.key === "Enter") handleSendMessage();
    };

    if (!isOpen) return null;

    return (
        <div
            style={{
                position: "fixed",
                top: 0,
                left: 0,
                right: 0,
                bottom: 0,
                backgroundColor: "rgba(0,0,0,0.8)",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                zIndex: 1000,
            }}
        >
            <div
                style={{
                    width: "90%",
                    maxWidth: 600,
                    height: "80%",
                    backgroundColor: "#fff",
                    borderRadius: 20,
                    display: "flex",
                    flexDirection: "column",
                    overflow: "hidden",
                    boxShadow: "0 20px 60px rgba(0,0,0,0.3)",
                }}
            >
                {/* 对话框头部 */}
                <div
                    style={{
                        padding: "20px 24px",
                        borderBottom: "1px solid #e0e0e0",
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "space-between",
                        background:
                            "linear-gradient(90deg, #ff6b6b 0%, #ee5a24 100%)",
                        color: "#fff",
                    }}
                >
                    <div
                        style={{
                            display: "flex",
                            alignItems: "center",
                            gap: 12,
                        }}
                    >
                        <span
                            role="img"
                            aria-label="昆昆"
                            style={{ fontSize: 24 }}
                        >
                            🎤
                        </span>
                        <h3
                            style={{ margin: 0, fontSize: 20, fontWeight: 600 }}
                        >
                            昆昆语音助手
                        </h3>
                    </div>
                    <button
                        onClick={onClose}
                        style={{
                            background: "none",
                            border: "none",
                            color: "#fff",
                            fontSize: 24,
                            cursor: "pointer",
                            padding: 4,
                        }}
                    >
                        ✕
                    </button>
                </div>

                {/* 消息列表 */}
                <div
                    style={{
                        flex: 1,
                        padding: "20px",
                        overflowY: "auto",
                        display: "flex",
                        flexDirection: "column",
                        gap: 16,
                    }}
                >
                    {messages.map((message, index) => (
                        <div
                            key={index}
                            style={{
                                display: "flex",
                                justifyContent:
                                    message.type === "user"
                                        ? "flex-end"
                                        : "flex-start",
                            }}
                        >
                            <div
                                style={{
                                    maxWidth: "70%",
                                    padding: "12px 16px",
                                    borderRadius: 18,
                                    backgroundColor:
                                        message.type === "user"
                                            ? "#e8f4fd"
                                            : "#fff3e0",
                                    color:
                                        message.type === "user"
                                            ? "#000"
                                            : "#333",
                                    fontSize: 16,
                                    lineHeight: 1.4,
                                    border:
                                        message.type === "user"
                                            ? "1px solid #b3d9ff"
                                            : "1px solid #ffcc80",
                                    position: "relative",
                                }}
                            >
                                {message.content}
                                {message.isVoice && (
                                    <span
                                        style={{
                                            position: "absolute",
                                            top: -8,
                                            right: -8,
                                            fontSize: 12,
                                            background: "#ff6b6b",
                                            color: "#fff",
                                            borderRadius: "50%",
                                            width: 20,
                                            height: 20,
                                            display: "flex",
                                            alignItems: "center",
                                            justifyContent: "center",
                                        }}
                                    >
                                        🎤
                                    </span>
                                )}
                            </div>
                        </div>
                    ))}
                </div>

                {/* 输入区域 */}
                <div
                    style={{
                        padding: "20px",
                        borderTop: "1px solid #e0e0e0",
                        display: "flex",
                        gap: 12,
                        alignItems: "center",
                    }}
                >
                    <input
                        type="text"
                        value={input}
                        onChange={(e) => setInput(e.target.value)}
                        onKeyDown={handleInputKeyDown}
                        placeholder="输入文字或点击麦克风说话..."
                        style={{
                            flex: 1,
                            padding: "12px 16px",
                            borderRadius: 25,
                            border: "2px solid #e0e0e0",
                            fontSize: 16,
                            outline: "none",
                        }}
                    />
                    <button
                        onClick={isListening ? stopListening : startListening}
                        style={{
                            width: "50px",
                            height: "50px",
                            borderRadius: "50%",
                            border: "none",
                            background: isListening
                                ? "linear-gradient(90deg, #ff6b6b 0%, #ee5a24 100%)"
                                : "linear-gradient(90deg, #667eea 0%, #764ba2 100%)",
                            color: "#fff",
                            fontSize: 20,
                            cursor: "pointer",
                            display: "flex",
                            alignItems: "center",
                            justifyContent: "center",
                            animation: isListening
                                ? "pulse 1s infinite"
                                : "none",
                        }}
                    >
                        {isListening ? "⏹️" : "🎤"}
                    </button>
                    <button
                        onClick={() => handleSendMessage()}
                        style={{
                            padding: "12px 24px",
                            borderRadius: 25,
                            border: "none",
                            background:
                                "linear-gradient(90deg, #667eea 0%, #764ba2 100%)",
                            color: "#fff",
                            fontSize: 16,
                            fontWeight: 600,
                            cursor: "pointer",
                        }}
                    >
                        发送
                    </button>
                </div>

                {/* 语音状态指示器 */}
                {(isListening || isSpeaking) && (
                    <div
                        style={{
                            position: "absolute",
                            top: "50%",
                            left: "50%",
                            transform: "translate(-50%, -50%)",
                            background: "rgba(0,0,0,0.8)",
                            color: "#fff",
                            padding: "20px 40px",
                            borderRadius: 20,
                            fontSize: 18,
                            fontWeight: 600,
                            zIndex: 1001,
                        }}
                    >
                        {isListening
                            ? "🎤 正在听你说话..."
                            : "🔊 昆昆正在说话..."}
                    </div>
                )}

                <style>{`
                    @keyframes pulse {
                        0% { transform: scale(1); }
                        50% { transform: scale(1.1); }
                        100% { transform: scale(1); }
                    }
                `}</style>
            </div>
        </div>
    );
};

export default VoiceAssistant;
